/**
 * Created by ziyu on 2017/9/14.
 */
/**
 * Created by yujianfu on 2016/11/16.
 */
import React, {Component, PropTypes} from 'react'
import moment from 'moment';
import {Form, Radio, DatePicker, Modal, Upload, Select, Input, Button, Icon, message} from 'antd';
import {origin, env} from '../../../utils/config'
import {fetchPost} from '../../../utils/request'

const FormItem = Form.Item;
const {MonthPicker, RangePicker} = DatePicker;

class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      size: 'default',
      fileList: [],
      params: {
        title: null,
        body: null,
        imageUrl: null,
        activityUrl: null,
      }
    };
  }

  state = {visible: false}
  showModal = () => {
    this.setState({
      visible: true,
    });
  }

  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    }, () => this.props.reload(Math.random()));
  };

  changeField(field, value) {

    this.setState({
      ...this.state,
      [field]: value,
    }, () => {
      this.props.changeParams(this.state);
    });
  }

  handleSubmit(e) {
    e.preventDefault();

    this.props.form.validateFields((error, values) => {
      if (!error) {
        var params = {};
        if (!values.imageUrl) {
          message.error('Please upload picture first')
          return false
        }
        params = {
          title: values.title,
          body: values.body,
          imageUrl: values.imageUrl.file.response.data.url,
          activityUrl: values.activityUrl,
        };

        this.create(params);
      }
    })
  }

  create(params) {
    fetchPost('/cms/activity/add', params).then(json => {
      if (json.code == 0) {
        message.info("Add success");
        this.handleReset()
      } else {
        message.error(json.msg);
      }
    });
  }

  handleReset(e) {
    this.props.form.resetFields();
    this.setState({
      effectiveStart: null,
      effectiveEnd: null,
      name: "",
      visible: false,
      pictureUrl: null,
      fileList: []
    }, () => {
      this.props.changeParams()
    });
  }

  handleUpload(info) {
    if (info) {
      let fileList = info.fileList;
      fileList = fileList.slice(-1);
      this.setState({fileList,});
    }
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    const size = this.state.size;

    const formItemLayout = {
      labelCol: {span: 8},
      wrapperCol: {span: 12},
    };
    return (
      <Form inline>
        <FormItem>
          &nbsp;&nbsp;&nbsp;
          <Button type="primary" size={size} onClick={this.showModal}>New Activity</Button>
          <Modal
            visible={this.state.visible}
            onCancel={() => {
              this.handleReset()
            }}
            footer={null}
          >
            <div style={{paddingTop: '30'}}>
              <Form style={{width: '100%', margin: 'auto'}} horizontal onSubmit={(e) => this.handleSubmit(e)}>
                <FormItem
                  {...formItemLayout}
                  label="Title"
                >
                  {getFieldDecorator('title', {
                    rules: [
                      {required: true, message: 'Title is necessary!'},
                      {
                        pattern: /^[a-zA-Z0-9.! @?,]*$/,
                        message: "Please enter the valid title!"
                      }
                    ],
                  })(
                    <Input />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="Body"
                >
                  {getFieldDecorator('body', {
                    rules: [
                      {required: true, message: 'Body is necessary!'},
                      {
                        pattern: /^[a-zA-Z0-9.! @?,]*$/,
                        message: "Please enter the valid body!"
                      }
                    ],
                  })(
                    <Input />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="Activity Url"
                >
                  {getFieldDecorator('activityUrl', {
                    rules: [
                      {required: true, message: 'Activity url is necessary!'},
                    ]
                  })(
                    <Input />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="Picture"
                >
                  {getFieldDecorator('imageUrl')(
                    <Upload onChange={this.handleUpload.bind(this)} defaultFileList={this.state.fileList} name="file"
                            fileList={this.state.fileList} action={origin + "/upload/img"} listType="picture">
                      <Button type="ghost">
                        <Icon type="upload"/> Upload
                      </Button>
                    </Upload>
                  )}
                </FormItem>
                <FormItem wrapperCol={{span: 12, offset: 8}}>
                  <Button type="primary" htmlType="submit">Add</Button>
                  &nbsp;
                  <Button type="ghost" onClick={(e) => this.handleReset(e)}><Icon type="reload"/></Button>
                </FormItem>
              </Form>
            </div>

          </Modal>
        </FormItem>


      </Form>
    )
  }
}

Index = Form.create()(Index);
export default Index;


